package com.liuyubo.sort;

import java.util.Arrays;

public class MergeSortBU implements Sort {
    @Override
    public void sort(int[] arr) {
        mergeSortBU(arr, arr.length);
    }

    void mergeSortBU(int[] arr, int n){

//    for( int sz = 1; sz <= n ; sz += sz )
//        for( int i = 0 ; i < n ; i += sz+sz )
//            // 对 arr[i...i+sz-1] 和 arr[i+sz...i+2*sz-1] 进行归并
//            __merge(arr, i, i+sz-1, min(i+sz+sz-1,n-1) );

        // Merge Sort Bottom Up 优化
        for( int i = 0 ; i < n ; i += 16 ) {
            InsertionSort.insertionSort(arr, i, Math.min(i + 15, n - 1));
        }

        for( int sz = 16; sz <= n ; sz += sz ) {
            for (int i = 0; i < n - sz; i += sz + sz) {
                if (arr[i + sz - 1] > arr[i + sz]) {
                    merge(arr, i, i + sz - 1, Math.min(i + sz + sz - 1, n - 1));
                }
            }
        }
    }

    /**
     * 将arr[l...mid]和arr[mid+1...r]两部分进行归并
     * @param arr
     * @param l
     * @param mid
     * @param r
     */
    private void merge(int[] arr, int l, int mid, int r) {
        int[] aux = new int[r - l + 1];
        for (int i = l; i <= r; i++) {
            aux[i - l] = arr[i];
        }
        int i = l, j = mid + 1;
        for (int k = l; k <= r; k++) {
            if (i > mid) {
                arr[k] = aux[j - l];
                j ++;
            } else if (j > r) {
                arr[k] = aux[i - l];
                i ++;
            } else if (aux[i - l] < aux[j - l]) {
                arr[k] = aux[i - l];
                i ++;
            } else {
                arr[k] = aux[j - l];
                j ++;
            }
        }
    }

    @Override
    public String getName() {
        return "Merge Sort BU";
    }

    public static void main(String[] args) {
        int[] arr = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
        MergeSortBU sort = new MergeSortBU();
        sort.sort(arr);
        Arrays.stream(arr).forEach(System.out::println);
    }
}
